/**
 * iWeb2GooglePages - Converts export iWeb content and uploads it to GPs.
 * Copyright (C) 2008 Will Droste
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */
package org.iweb2gps;

import java.io.File;
import java.text.MessageFormat;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.OnbeforeunloadHandler;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlFileInput;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSpan;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class Upload {

    private final static String URL_TEMPLATE = "http://pages.google.com/a/{0}";
    /**
     * URL Template for the Google Pages Service.
     */
    final private String domain;
    final private String username;
    final private String password;
    final private WebClient client;
    
    /**
     * Current Page the Web Client is on..
     */
    private HtmlPage current;

    /**
     * Uploads a directory of files to Google Pages.
     */
    public Upload(String domain, String username, String password) {
        this.domain = domain;
        this.username = username;
        this.password = password;
        this.client = new WebClient(BrowserVersion.FIREFOX_2);
        this.client.setOnbeforeunloadHandler(new OnbeforeunloadHandler() {
            public boolean handleEvent(Page page, String message) {
                return true;
            }
        });
    }

    public void login() throws Exception {
        // determine if the browser is logged in before proceeding...
        if (isLoggedIn(getCurrentPage())) {
            return;
        }
        // Get the first page
        final String url = MessageFormat.format(URL_TEMPLATE, this.domain);
        final HtmlPage page1 = (HtmlPage) client.getPage(url);

        // Get the form that we are dealing with and within that form,
        // find the submit button and the field that we want to change.
        final HtmlForm form = page1.getFormByName("login");
        final HtmlTextInput userField = (HtmlTextInput) form
                .getInputByName("userName");
        // Change the value of the text field
        userField.setValueAttribute(this.username);
        final HtmlPasswordInput passwordField = (HtmlPasswordInput) form
                .getInputByName("password");
        passwordField.setValueAttribute(this.password);
        // get the submit button..
        final HtmlSubmitInput submit = (HtmlSubmitInput) form
                .getInputByValue("Sign In");
        // Now submit the form by clicking the button and get back the
        // second page.
        HtmlPage googlePages = (HtmlPage) submit.click();
        // check to make sure that we've logged in..
        if (!isLoggedIn(googlePages)) {
            throw new IllegalStateException("Failed to login!");
        }
        setCurrentPage(googlePages);        
    }
    public void logout() throws Exception {
        HtmlPage page = getCurrentPage();
        if (isLoggedIn(page)) {
            // Sign Out..
            ((HtmlSpan) page.getByXPath(SIGN_OUT).get(0)).click();
        }
    }
    final String CANCEL_DOWNLOAD = "//span[contains(text(),'cancel upload')]";
    final String SIGN_OUT = "//span[contains(text(),'Sign out')]";

    public void upload(File file) throws Exception {
        HtmlPage page = getCurrentPage();
        
        // click the upload link..
        final String CLICK_UPLOAD = "//span[@id='tr_toggle-upload-form']";
        ((HtmlSpan) page.getByXPath(CLICK_UPLOAD).get(0)).click();
        
        // find the file input element..
        final String FILE_INPUT = "//input[@type='file']";
        final Object obj = page.getByXPath(FILE_INPUT).get(0);
        final HtmlFileInput input = (HtmlFileInput) obj;
        input.setValueAttribute(file.toString());
        // click and see what happens..
        page = (HtmlPage)input.click();
        
        // check if file is there 'alert(TR_files._array[0].name);'
        // set some handlers to determine changed window.. 
        
        // look for the page to change and the make of TR_files
        //TR_pages.get(1).set("homepage", true);
        //var TR_files = TR_ItemList.createFromArrays(
        //[ "name", "url", "size" ],
        //[
        //"About_Me.html",
        //"About_Me.html",
        //14065
        //,
        //"About_Me_files_200223987-001a.png",
        //"About_Me_files_200223987-001a.png",
        //5776
        //,
        //"About_Me_files_55843702a.png",
        //"About_Me_files_55843702a.png",
        //4553
        //,
    }

    /**
     * Determine if 'Sign Out' is present on the page.
     */
    private static boolean isLoggedIn(HtmlPage page) throws Exception {
        boolean ret = false;
        if (page != null) {
            final String SIGN_OUT = "//span[contains(text(),'Sign out')]";
            ret = !page.getByXPath(SIGN_OUT).isEmpty();
        }
        return ret;
    }
    
    
    private void setCurrentPage(HtmlPage page) {
        this.current = page;
    }
    private HtmlPage getCurrentPage() {
        return this.current;
    }    
}
